<?php

namespace app\admin\controller\user;

use think\Controller;
use think\Request;
use app\common\controller\Admin;

class Draw extends Admin
{
    protected $model = null;
    public function initialize()
    {
        parent::initialize();
        $this->model = model('Draw');
    }
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        if ($this->request->isAjax())
        {
            $map = [
                ['status','neq',-1]
            ];
            $uid = (int)input('uid',0);
            if ($uid>0){
                $map[] = ['uid','=',$uid];
            }
            //待审核
            $status = input('status');
            if (isset($status) && $status!=''){
                $map[] = ['status','=',$status];
            }
            //时间条件
            $data = input('date');
            if ($data){
            	list($date_start,$date_end) = str2arr($data,' ~ ');
            	$map[] = ['create_time','between time',[$date_start,$date_end]];
            }
            $list = $this->model
            ->where($map)
            ->order('create_time desc')
            ->paginate(input('limit',15));
            $list->append(['user_nickname','status_text','draw_type_text']);
            //返回layui分页
            return json(layui_page($list));
        }
        //统计，今日提现所有申请
        $today_total = $this->model->whereTime('create_time','today')->sum('money');
        //累积提现，支付成功
        $all_total = $this->model->where('status',1)->sum('money');
        $this->assign('today_total',$today_total);
        $this->assign('all_total',$all_total);
        return $this->fetch();
    }
    /**
     * 微信打款
     */
    public function wx_pay()
    {
        $id = intval(input('id'));
        if (empty($id)) $this->error('请选择要操作的数据');
        $info = model('Draw')->get($id);
        if ($info){
            if ($info->status!=0){
                $this->error('已经处理过，不要重复打款');
            }else {
                //开始付钱
                try {
                    $openid = db('User')->where('uid',$info->uid)->value('wxopen_openid');
                    $desc = '余额提现';
                    require_once env('extend_path').'payment/wxpay/ComPay.php';
                    $cp = new \ComPay1();
                    $cp->setReOpenid($openid);
                    $cp->setTotalAmount($info->money*100);
                    $cp->setDesc($desc);
                    $data = $cp->ComPay();
                    if ($data['result_code']=='SUCCESS' && $data['return_code'] == 'SUCCESS'){//支付成功
                        $info->status = 1;
                        $info->save();
                        $this->success('打款成功');
                    }else{
                        $this->error('打款失败:'.$data['err_code'].':'.$data['err_code_des']);
                    }
                }catch (\Exception $e){
                    $this->error($e->getMessage());
                }
                
            }
        }else {
            $this->error('信息不存在~');
        }
    }
    /**
     * 标记打款
     */
    public function mark_pay()
    {
        $id = intval(input('id'));
        if (empty($id)) $this->error('请选择要操作的数据');
        $info = model('Draw')->get($id);
        if ($info){
            if ($info->status!=0){
                $this->error('已经处理过，不要重复打款');
            }else {
                //开始处理
                $info->status = 3;
                $info->save();
                $this->success('标记打款成功');
            }
        }else {
            $this->error('信息不存在~');
        }
        
    }
    /**
     * 驳回
     */
    public function down_pay()
    {
        $id = intval(input('id'));
        if (empty($id)) $this->error('请选择要操作的数据');
        $info = model('Draw')->get($id);
        if ($info){
            if ($info->status!=0){
                $this->error('已经处理过，不要重复打款');
            }else {
                //开始处理
                $info->status = 2;
                if($info->save()){
                    add_money('draw_money_refund', $info->uid,['money'=>$info->money_rel,'remark'=>'余额提现驳回']);
                    $this->success('已驳回，退款至账户余额');
                }else {
                    $this->error('操作失败');
                }
                
            }
        }else {
            $this->error('信息不存在~');
        }
    }
    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function del($ids='')
    {
        parent::del($ids);
    }
    /**
     * 支付宝打款
     */
    public function alipay()
    {
        $id = intval(input('id'));
        if (empty($id)) $this->error('请选择要操作的数据');
        $info = model('Draw')->get($id);
        if ($info){
            if ($info->status!=0){
                $this->error('已经处理过，不要重复打款');
            }else {
                //开始付钱
                include env('extend_path').'/payment/alipay/AopSdk.php';
                $alipay_cfg_wap = get_db_config(true)['alipay_cfg_wap'];
                $aop = new \AopClient ();
                $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
                $aop->appId = $alipay_cfg_wap['app_id_draw'];
                $aop->rsaPrivateKey = $alipay_cfg_wap['merchant_private_key_draw'];
                $aop->alipayrsaPublicKey=$alipay_cfg_wap['alipay_public_key_draw'];
                $aop->apiVersion = '1.0';
                $aop->postCharset='UTF-8';
                $aop->format='json';
                $aop->signType='RSA2';
                $request = new \AlipayFundTransToaccountTransferRequest ();
                $out_biz_no = build_order_no().$info['uid'];//32位
                $content = [
                    'out_biz_no' => $out_biz_no,
                    'payee_type' => 'ALIPAY_LOGONID',
                    'payee_account' => $info['alipay_account'],
                    'amount' => $info['money'],
                    'payer_show_name' => config('site.name'),
                    'payee_real_name' => $info['real_name'],
                    'remark' => '提现',
                ];
                $request->setBizContent(json_encode($content));
                $result = $aop->execute ( $request);
                
                $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
                $resultCode = $result->$responseNode->code;
                if(!empty($resultCode)&&$resultCode == 10000){
                    $info->status = 1;
                    $info->out_biz_no = $result->$responseNode->out_biz_no;
                    $info->out_no = $result->$responseNode->order_id;
                    $info->save();
                    $this->success('打款成功');
                } else {
                    $this->error('打款失败:'.$resultCode.':'.$result->$responseNode->msg);
                }
                
            }
        }else {
            $this->error('信息不存在~');
        }
        
    }
    /**
     * 导出会员列表、提现记录、支付记录
     */
    public function export()
    {
    	$params = input();
    	$ids = $params['ids'] ?? [];
    	$type = empty($params['type'])?'draw':$params['type'];
    	$map = [];
    	$map[] = ['status','neq',-1];
    	//无选中
    	if (empty($ids)){
    		//日期
    		if ($params['date']){
    			list($date_start,$date_end) = str2arr($params['date'],' ~ ');
    		}else{
    			$date_start = date('Y-m-d 00:00:00',time());
    			$date_end = date('Y-m-d 23:59:59',time());
    		}
    		$map[] = ['create_time','between time',[$date_start,$date_end]];
    	}else {
    		$map[] = ['id','in',$ids];
    	}
    	//搜索
    	$uid = (int)input('uid',0);
    	if ($uid>0){
    		$map[] = ['uid','=',$uid];
    	}
    	//状态
    	$status = input('status');
    	if (isset($status) && $status!=''){
    		$map[] = ['status','=',$status];
    	}
    	switch ($type){
    		case 'draw':
    			$list = $this->model->where($map)->field('uid,money,money_rel,real_name,alipay_account,mobile,create_time,status,update_time')->select();
    			$status_arr = ['待审核','提现成功','提现驳回','标记成功'];
    			foreach ($list as $k=>$v){
    				$list[$k]['status'] = $status_arr[$v['status']];
    			}
    			$headArr = ['用户ID','实际打款','提现金额','真实姓名','支付宝','手机','申请时间','处理状态','处理时间'];
    			//设置一些宽度
    			$width = [
    				'E' => 20,
    				'F' => 20,
    				'G' => 20,
    				'I' => 20,
    			];
    			set_time_limit(0);
    			ini_set("memory_limit", "2048M");
    			export_excel('提现记录', $headArr, $list->toArray(),$width);
    			break;
    	}
    }
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
}
